package com.ddsfec.loginapi.user.controller;

import com.ddsfec.loginapi.user.entity.JsonResultVo;
import com.ddsfec.loginapi.user.entity.User;
import com.ddsfec.loginapi.user.service.UserService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@RestController
@RequestMapping("user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping("add")
    public JsonResultVo addUser(@RequestBody User user){
        System.out.println(user+"<<<<<<<<<<<<<<<");
        try {
            userService.insertUser(user);
            return JsonResultVo.createSuccessJsonResult(user);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResultVo.createFailJsonResult("0","用户添加失败");
        }
    }

    /**
     * 登录
     * @param user
     * @return
     */

    @RequestMapping("login")
    public JsonResultVo login(@RequestBody User user){
        System.out.println("-----------"+user.getUserName()+":"+user.getPassword());
        try {
            User user1 = userService.query(user.getUserName(),user.getPassword());
            if(user1 != null){

                //登录认证成功
                //生成token
                JwtBuilder builder = Jwts.builder();
                builder.setSubject(user1.getUserName());

                //设置token的有效时间
                long time = System.currentTimeMillis();
                builder.setIssuedAt(new Date(time));
                builder.setExpiration(new Date(time+60*60*1000));

                builder.setId(user1.getUserId());

                //设置token的生成密码，用于校验
                builder.signWith(SignatureAlgorithm.HS256,"sh-qianfeng1234");

                //生成token
                String token = builder.compact();
                return JsonResultVo.createSuccessJsonResult(token);
            }else{
                return JsonResultVo.createFailJsonResult("0","用户登录失败！");
            }
        } catch (Exception e) {
            //e.printStackTrace();
            return JsonResultVo.createFailJsonResult("0","用户登录失败！");
        }
    }

}
